<template>
  <a-card v-if="!(toolbarSettings.commonInfo.processStatus === 'isDraft')" :bordered="false" size="small" title="流程跟踪">
    <template #extra>流程已启动：{{ startTime }} &nbsp; &nbsp;<a-button key="3">取消跟踪</a-button>
    </template>
  </a-card>
  <br />
  <a-card v-if="toolbarSettings.commonInfo.processStatus === 'isHistory'" :bordered="false" title="操作">
    <a-radio-group v-model:value="historyOperation" name="rdHistoryOperation">
      <a-radio v-for="item in toolbarSettings.operationTemplate" :value="item.operationType">{{
        item.operationName
      }}</a-radio>
      <!--
      <a-radio value="discard">废弃</a-radio>
      <a-radio value="reminder">催办</a-radio>
      <a-radio value="recall">撤回</a-radio>
      <a-radio value="circulate">传阅</a-radio>
      -->
    </a-radio-group>
    <a-card :bordered="false" size="small" title="催办设置" v-if="historyOperation === 'reminder'">
      催办方式：
      <template>
        <a-checkbox-group v-model:value="reminderCheckedList" :options="reminderOptions" />
      </template>
    </a-card>
  </a-card>  
  <a-card v-if="toolbarSettings.commonInfo.processStatus === 'isOnway'" :bordered="false" title="操作">
    <a-radio-group v-model:value="operation" name="rdOperation">
      <a-radio v-for="item in toolbarSettings.operationTemplate" :value="item.operationType">{{
        item.operationName
      }}</a-radio>
      <!--
      <a-radio value="approve">通过</a-radio>
      <a-radio value="reject">驳回</a-radio>
      <a-radio value="transfer">转办</a-radio>
      <a-radio value="communicate">沟通</a-radio>
      <a-radio value="discard">废弃</a-radio>
      <a-radio value="signature">加签</a-radio>            
      <a-radio value="circulate">传阅</a-radio>
      -->
    </a-radio-group>
    <a-card :bordered="false" size="small" title="转办人员设置" v-if="operation == 'transfer'">
      <a-form-item name="transferer" label-align="left">
        <div style="
            border: 1px solid #e6e8eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
          ">
          <a-space>
            <div style="overflow: auto" class="tagboxs">
              <a-tag closable @close="handleTransferClose()" v-for="tag in toolbarSettings.transferToUserName"
                :key="tag">
                {{ tag }}
              </a-tag>
            </div>
          </a-space>
          <a-tooltip title="请选转办人员">
            <n-button style="margin-left: auto" size="small" secondary type="info" @click="openModal">
              <template #icon>
                <UserOutlined />
              </template>
            </n-button>
          </a-tooltip>
        </div>
      </a-form-item>
    </a-card>
    <br />
    <a-card :bordered="false" size="small" title="驳回设置" v-if="operation == 'reject'">
      驳回到：
      <a-select style="width: 120px" v-model:value="rejectActivi"
        :options="toolbarSettings.rejectToActivities"></a-select>
      <br />
      节点通过后：
      <a-select v-model:value="rejectPath" style="width: 240px" @focus="focus" @change="handleChange">
        <a-select-option value="0">按顺序流转</a-select-option>
        <a-select-option value="1">返回我</a-select-option>
        <a-select-option value="2">返回这个节点所有人</a-select-option>
        <a-select-option value="3">返回指定节点</a-select-option> </a-select>&nbsp;&nbsp;&nbsp;
      <a-select style="width: 120px" v-show="rejectPath == '3'" v-model:value="afterActivityId"
        :options="toolbarSettings.rejectToActivities"></a-select>
    </a-card>
    <br />
    <a-card :bordered="false" size="small" title="加签设置" v-if="operation == 'signature'">
      加签类型：
      <a-radio-group v-model:value="signatureType" name="radioGroupSignature">
        <a-radio value="beforemeSignature">在我审批前加签</a-radio>
        <a-radio value="aftermeSignature">在我审批后加签</a-radio>
      </a-radio-group>
      <br />
      <a-form-item label="加签人员：" name="signatureleader" label-align="left">
        <div style="
            border: 1px solid #e6e8eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
          ">
          <a-space>
            <div style="overflow: auto" class="tagboxs">
              <a-tag closable @close="handleCloseSignature(toolbarSettings.signaturePersons)"
                v-for="tag in toolbarSettings.signaturePersons" :key="tag">
                {{ tag }}
              </a-tag>
            </div>
          </a-space>
          <a-tooltip title="请选择加签人员">
            <n-button style="margin-left: auto" size="small" secondary type="info"
              @click="openUserModal(null, 'signature')">
              <template #icon>
                <UserOutlined />
              </template>
            </n-button>
          </a-tooltip>
        </div>
      </a-form-item>
      <br />
    </a-card>
    <a-card :bordered="false" size="small" title="沟通设置" v-if="operation == 'communicate'">
      <a-form-item label="沟通人员：" name="communicateleader" label-align="left">
        <div style="
            border: 1px solid #e6e8eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
          ">
          <a-space>
            <div style="overflow: auto" class="tagboxs">
              <a-tag closable @close="handleCloseCommunicate(toolbarSettings.communicatePersons)"
                v-for="tag in toolbarSettings.communicatePersons" :key="tag">
                {{ tag }}
              </a-tag>
            </div>
          </a-space>
          <a-tooltip title="请选择沟通人员">
            <n-button style="margin-left: auto" size="small" secondary type="info"
              @click="openUserModal(null, 'communicate')">
              <template #icon>
                <UserOutlined />
              </template>
            </n-button>
          </a-tooltip>
        </div>
      </a-form-item>
    </a-card>
    <a-card :bordered="false" size="small" title="传阅设置" v-if="operation == 'circulate'">
      <a-form-item label="传阅对象：" name="circulateleader" label-align="left">
        <div style="
            border: 1px solid #e6e8eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
          ">
          <a-space>
            <div style="overflow: auto" class="tagboxs">
              <a-tag closable @close="handleCloseCommunicate(toolbarSettings.circulatePersons)"
                v-for="tag in toolbarSettings.circulatePersons" :key="tag">
                {{ tag }}
              </a-tag>
            </div>
          </a-space>
          <a-tooltip title="请选择传阅对象">
            <n-button style="margin-left: auto" size="small" secondary type="info"
              @click="openUserModal(null, 'circulate')">
              <template #icon>
                <UserOutlined />
              </template>
            </n-button>
          </a-tooltip>
        </div>
      </a-form-item>
    </a-card>

  </a-card>
  <a-card v-if="toolbarSettings.commonInfo.processStatus === 'isAppended'" :bordered="false" title="操作">
    <a-radio-group v-model:value="appendTaskType" name="rgAppended">
      <a-radio v-if="toolbarSettings.commonInfo.processSubStatus === 'signaturePass'"
        value="signaturePass">加签通过</a-radio>
      <a-radio v-if="toolbarSettings.commonInfo.processSubStatus === 'recallSignature'"
        value="recallSignature">收回加签</a-radio>
      <a-radio v-if="toolbarSettings.commonInfo.processSubStatus === 'communicatePass'"
        value="communicatePass">沟通回复</a-radio>
      <a-radio v-if="toolbarSettings.commonInfo.processSubStatus === 'recallCommunicate'"
        value="recallCommunicate">收回沟通</a-radio>
    </a-radio-group>
  </a-card>
  <br v-if="!(toolbarSettings.humanSelectNodes.length == 0)" />
  <a-card v-if="!(toolbarSettings.humanSelectNodes.length == 0)" title="选择流程走向">
    <a-radio-group v-model:value="humanSelect" name="rgFlowway">
      <a-radio v-for="item in toolbarSettings.humanSelectNodes" :value="item.flowElementId">{{
        item.flowElementName
      }}</a-radio>
    </a-radio-group>
  </a-card>
  <br v-if="!(toolbarSettings.modifyNodes.length == 0)" />
  <a-card v-if="!(toolbarSettings.modifyNodes.length == 0)" title="修改节点处理人">
    <template v-for="item in toolbarSettings.modifyNodes">
      <a-form-item :label="item.nodeName" name="leader" label-align="left">
        <div style="
            border: 1px solid #e6e8eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
          ">
          <a-space>
            <div style="overflow: auto" class="tagboxs">
              <a-tag closable @close="handleClose(item)" v-for="tag in item.nodeValues" :key="tag">
                {{ tag }}
              </a-tag>
            </div>
          </a-space>
          <a-tooltip title="请选择处理人">
            <n-button style="margin-left: auto" size="small" secondary type="info" @click="openUserModal(item, null)">
              <template #icon>
                <UserOutlined />
              </template>
            </n-button>
          </a-tooltip>
        </div>
      </a-form-item>
    </template>
  </a-card>
  <a-card>
    <div>
          <preview
            v-if="showPreview && previewConfig?.form_type == '0'"
            ref="previewRef"
            v-bind="{ ...previewFormObj }"
          ></preview>
          <iframe
            ref="previewIframeRef"
            v-if="previewConfig.form_type == '1'"
            :src="previewIframeUrl"
            class="h-full w-full"
            frameborder="0"
          ></iframe>
          <a-card
            v-if="!isNullOrUnDef(previewConfig.procinstid) && !isEmpty(previewConfig.procinstid)"
          >
            <schema-form ref="dynamicForm" v-bind="formProps" @submit="confirm"> </schema-form>
          </a-card>
        </div>
  </a-card>
  <br />
  <a-card :bordered="false" size="small" title="处理意见">
    <a-textarea v-model:value="userRquest.comments" placeholder="请输入处理意见" :auto-size="{ minRows: 2, maxRows: 5 }" />
    <br /><br />
    <a-upload v-model:file-list="fileList" :before-remove="removeFile" :action="api.uploadfiles" >
      <a-button>
        <upload-outlined></upload-outlined>
        上传附件
      </a-button>
      <template #itemRender="{ file, actions }">
        <a-space>
          <span>{{ file.name }}</span>
          <a href="javascript:;" @click="actions.download">预览</a>
          <a href="javascript:;" @click="actions.download">下载</a>
          <a href="javascript:;" @click="handleRemove(file)">删除</a>
        </a-space>
      </template>
    </a-upload>
    <br />
    <a-button type="primary" @click="appoveOperation">提交</a-button>
    <a-button type="primary" @click="printFiles">测试</a-button>
  </a-card>
  <a-card :bordered="false" size="small">
    <a-collapse v-model:activeKey="activeKey1" :bordered="false" style="background: rgb(255, 255, 255)">
      <template #expandIcon="{ isActive }">
        <caret-down-outlined :rotate="isActive ? 180 : 0" />
      </template>
      <a-collapse-panel key="1" header="流程走向" :style="customStyle">
        <p>当前节点：</p>
        <p>{{ toolbarSettings.willgoNode.currentNodeInfo }}</p>
        <p>下一节点：</p>
        <p>{{ toolbarSettings.willgoNode.nextNodeInfo }}</p>
      </a-collapse-panel>
    </a-collapse>
  </a-card>  
</template>

<script lang="tsx" setup>
import { ref, nextTick, reactive, unref, onMounted, watch, defineComponent } from 'vue';
import { useApproveToolbar } from './useApproveToolbar';
import { isEmpty, isNullOrUnDef } from '@/utils/is/';
import constants from '@/utils/constants';
import { UploadOutlined } from '@ant-design/icons-vue';
import { message, type UploadProps } from 'ant-design-vue';
import { CaretDownOutlined, UserOutlined } from '@ant-design/icons-vue';
import {
  userCommunicateRequest, userSaveWorkflowDraftRequest, userApproveRequest,
  userDiscardRequest, userRejectRequest, userTaskOperationRequest, userTransferRequest,
  userRecallRequest, userSignatureRequest, activityApproveUser, UserAppendRequest, 
  userCirculateRequest,userReminderRequest
} from './userApproveRequest';
import { getRejectActivities, getToolbarSettings } from '@/api/flow/review';
import type { SelectProps } from 'ant-design-vue';
import { useModal } from '@/hooks/useModal/useModal';
import type { FormInstance } from 'ant-design-vue';
import userMore from '@/components/system/orgUserMore/userMore.vue';
import userSingle from '@/components/system/orgUserSingle/userSingle.vue';
import api from '@/core/permission/modules/form/index';
import { useUserStore } from '@/store/modules/user';
import {deleteFile} from '@/api/form/index';
import preview from '@/components/form/preview.vue';

defineComponent({
  userSingle,
  userMore
}
)
const printFiles = () => {
  console.log(fileList);
}

const onSubMit = () => {
  return [null, null]
};
const handleClose = (item) => {
  item.nodeValues = [];
  item.selectedNodeValues = "";
}
//附件删除事件
const handleRemove = async(file: any) => {
  console.log(file,"1111111")
  console.log(fileList,"2222222")
  const index = fileList.value.findIndex(item => item.uid === file.uid);
  if (index !== -1) {
    fileList.value.splice(index, 1);
    const res=await deleteFile({filePath:file.response.result.filePath})
  }
};
const handleCloseSignature = (persons) => {
  persons = [];
}
const handleCloseCommunicate = (persons) => {
  persons = [];
}
const userStore = useUserStore();
const editDrawerBindValue = reactive({
  defaultSelectData: [],
  selectedKey: ''
});

const handleTransferClose = () => {
  toolbarSettings.transferToUserName = [];
  transferToUserId.value = "";
}
const reminderCheckedList = ref(["todo", "shortmessage"]);
const reminderOptions = [
{ label: '待办', value: 'todo', disabled: true },
{ label: '邮件', value: 'email', },
{ label: '短信', value: 'shortmessage',  }  
];



const [ModalRender, modalRef] = useModal();
const userSingleRef = ref<FormInstance>();
const openModal = async () => {
  ModalRender.show({
    title: '选择处理人员',
    width: '70%',
    // 是否显示右上角确定取消
    defaultExtra: true,
    destroyOnClose: true,
    content: () => {
      return <userSingle ref={userSingleRef} defaultData={unref(editDrawerBindValue)}></userSingle>;
    },
    // 确定方法执行
    onOk: async (values) => {
      const res = await userSingleRef.value?.handleSubmit();
      if (!res) return;
      toolbarSettings.transferToUserName.push(res.NAME);
      transferToUserId.value = res.NO;
      // groupInfo.leader=res.NO;
    },
  });
};
const openUserModal = async (item, operation) => {
  if (item == null)
    editDrawerBindValue.selectedKey = operation;
  else
    editDrawerBindValue.selectedKey = item.nodeKey;
  ModalRender.show({
    title: '选择处理人员',
    width: '70%',
    // 是否显示右上角确定取消
    defaultExtra: true,
    destroyOnClose: true,
    content: () => {
      return <userMore ref={userSingleRef} defaultData={unref(editDrawerBindValue)} > </userMore>;
    },
    // 确定方法执行
    onOk: async (values) => {
      const res = await userSingleRef.value?.handleSubmit();
      if (!res) return;
      if (res.length > 0) {
        updateSelected(res);
      }
    },
  });
};


const updateSelected = (selectedperson) => {
  let selecedkey = selectedperson[0].selected;
  if (selecedkey == "signature") {
    signatureUsers.value = "";
    let newSelected = "";
    selectedperson.forEach(element => {
      newSelected += element.NAME + ",";
      signatureUsers.value += element.NO + ",";
    });
    newSelected = newSelected.substring(0, newSelected.length - 1);
    signatureUsers.value = signatureUsers.value.substring(0, newSelected.length - 1);
    toolbarSettings.signaturePersons = newSelected.split(",");
    return;
  }
  if (selecedkey == "communicate") {
    communicateUsers.value = "";
    let newSelected = "";
    selectedperson.forEach(element => {
      newSelected += element.NAME + ",";
      communicateUsers.value += element.NO + ",";
    });
    newSelected = newSelected.substring(0, newSelected.length - 1);
    communicateUsers.value = communicateUsers.value.substring(0, newSelected.length - 1);
    toolbarSettings.communicatePersons = newSelected.split(",");
    return;
  }

  if (selecedkey == "circulate") {
    circulateUsers.value = "";
    let newSelected = "";
    selectedperson.forEach(element => {
      newSelected += element.NAME + ",";
      circulateUsers.value += element.NO + ",";
    });
    newSelected = newSelected.substring(0, newSelected.length - 1);
    circulateUsers.value = circulateUsers.value.substring(0, newSelected.length - 1);
    toolbarSettings.circulatePersons = newSelected.split(",");
    return;
  }


  let slectedNode = toolbarSettings.modifyNodes.filter(obj => obj.nodeKey == selecedkey);
  let newSelected = "";
  let taskrundata = "";
  selectedperson.forEach(element => {
    newSelected += element.NAME + ",";
    taskrundata += `{"NO":"${element.NO}","NAME":"${element.NAME}","ORG_TYPE":"user"},`;
  });
  newSelected = newSelected.substring(0, newSelected.length - 1);
  slectedNode[0].nodeValues = newSelected.split(",");
  taskrundata = "[" + taskrundata + "]";
  slectedNode[0].selectedNodeValues = taskrundata;
  console.log(slectedNode[0].selectedNodeValues);

}

const toolbarSettings = reactive({
  commonInfo: {
    createDatetime: ref(""),
    processStatus: "",
    processSubStatus: ""
  },
  selectedVaules: {
    humanNodeSelected: '',
    operation: "",
    rejectPath: "",
    rejectActivi: "",
    afterActivityId: "",
    transferToUserId: "",
    signatureType: "",
    signatureUsers: "",
    communicateUsers: "",
    circulateUsers: "",
  },
  transferToUserName: [],
  signaturePersons: [],
  communicatePersons: [],
  circulatePersons: [],

  //task的状态类型
  // isDraft: 草稿状态； isHistory: 历史或者草稿（对于当前登录用户）； isOnway:审批中； isAppended :追加任务
  //isCommunicated:沟通者； iscommunicatting 被沟通者；isSignatured:加签者；isSignaturing：被加签者；
  operationTemplate: [],
  rejectToActivities: [],
  modifyNodes: [
    /*
    {nodeName:'部门经理',nodeKey:'adferad',isRequired:false,nodeValues:'张三，里斯'},
    {nodeName:'总经理',nodeKey:'dfdasdf',isRequired:false,nodeValues:'王五，赵六'}
    */
  ],
  humanSelectNodes: [
    /*
  {flowElementName:'部门经理',flowElementId:'1'},  
  */
  ],
  willgoNode: {
    currentNodeInfo: '',
    nextNodeInfo: ''
  },
  attachments: [],
  comments: ""
});


const props = defineProps({
  previewFormObj: {
      type: Object as any,
      default: {
        itemList: [],
        formConf: {},
      },
    },
    previewConfig: {
      type: Object as any,
      default: {},
    },
});
const emit = defineEmits(['cancel']);

const startTime = ref("");
const operation = ref<string>('');
const humanSelect = ref("");
const historyOperation = ref("");
const rejectPath = ref('');
const rejectActivi = ref('');
const afterActivityId = ref('');
const rejectActivis = ref<SelectProps[]>([]);
const transferToUserId = ref('');
const signatureType = ref('aftermeSignature');
const signatureUsers = ref('');
const communicateUsers = ref('');
const circulateUsers = ref('');
const appendTaskType = ref('');


// 当前主键
const bussid = ref('');

const getModifyactivityApproveUsers = () => {
  let allnodes = [];
  toolbarSettings.modifyNodes.forEach(element => {
    if (element.selectedNodeValues) {
      if (element.selectedNodeValues != "") {
        let node: activityApproveUser = {
          activityId: element.nodeKey,
          users: element.selectedNodeValues,
        }
        allnodes.push(node);
      }
    }
  });
  return allnodes;

}


const focus = () => {
  console.log('focus');
};

const handleChange = (value: string) => {
  console.log(`selected ${value}`);
};
const userRquest = reactive({
  comments: '',
  processDefinitionId: '',
  taskId: '',
  businessKey: '',
  approveUserId: "",
});

const appoveOperation = () => {  
  //如果是草稿模式，分两种情况，一种是taskid，如果不为空，那么需要执行approve提交，如果为空，那么直接是发起
  userRquest.taskId = props.previewConfig.taskid;
  userRquest.approveUserId = userStore.getUserAccount;
  //todo: bug待确认
  if (props.previewConfig.isDraft||operation.value ==="") {    
    let toolbarBusinessContext = JSON.stringify(toolbarSettings);
    let allModifyNodes = [];
    allModifyNodes = getModifyactivityApproveUsers();
    let draft: userSaveWorkflowDraftRequest = {
      ...userRquest,      
      processInstanceId: props.previewConfig.procinstid,
      processDefinitionId: props.previewConfig.processDefinitionId,      
      activityApproveUsers: allModifyNodes,
      handSelectedActivityId: '',
      businessKey: bussid.value,
      toolbarSettings: toolbarBusinessContext,
      //从上面点击的暂存，是真草稿，这个直接发送了到下一步了，是启动
      isRealSaveDraft: false,
      comments: '',
    };
    actionClick('start', draft);
  }
  else if (operation.value === 'approve') {
    let allModifyNodes = [];
    allModifyNodes = getModifyactivityApproveUsers();
    let approveRequest: userApproveRequest;
    approveRequest = {
      ...userRquest,
      activityApproveUsers: allModifyNodes,
      handSelectedActivityId: '',
    };
    actionClick(operation.value, approveRequest);
  }
  else if (operation.value === 'reject') {
    if (rejectActivi.value === '') {
      message.error('请选择驳回节点！');
      return;
    }
    userRquest.taskId = props.previewConfig.taskid;
    let rejectRequest: userRejectRequest;
    rejectRequest = {
      ...userRquest,
      rejectToActivityId: rejectActivi.value,
      afterApprovePath: rejectPath.value,
      afterApproveActivityId: afterActivityId.value,
    };
    actionClick(operation.value, rejectRequest);
  }
  else if (operation.value === 'transfer') {
    let transRequset: userTransferRequest;
    transRequset = {
      ...userRquest,
      toUserId: transferToUserId.value
    }
    actionClick(operation.value, transRequset);
  } 
  else if (operation.value === 'signature') {
    let signatureRequest: userSignatureRequest;
    signatureRequest = {
      ...userRquest,
      signatureType: signatureType.value,
      signatureUsers: signatureUsers.value
    };
    actionClick(operation.value, signatureRequest);
  }
  else if (operation.value === 'communicate') {
    let communicateRequest: userCommunicateRequest;
    communicateRequest = {
      ...userRquest,
      communicateUsers: communicateUsers.value
    };
    actionClick(operation.value, communicateRequest);
  }
  else if (operation.value === "circulate") {
    let circulateRequest: userCirculateRequest;
    circulateRequest = {
      ...userRquest,
      circulateUsers: circulateUsers.value
    };
    actionClick(operation.value, circulateRequest);
  }  
  else if (toolbarSettings.commonInfo.processStatus === "isAppended") {
    let appendRequest: UserAppendRequest;
    appendRequest = {
      ...userRquest,
      appendTaskType: toolbarSettings.commonInfo.processSubStatus,
    };
    actionClick("append", appendRequest);
  }//  历史操作  废弃，撤回，传阅，催办
  else if (historyOperation.value === 'discard') {
    let discardRequest: userDiscardRequest;
    discardRequest = { ...userRquest };
    actionClick(historyOperation.value, discardRequest);
  }
  else if (historyOperation.value === 'recall') {
    let recallRequst: userRecallRequest;
    recallRequst = { ...userRquest, 
      processInstanceId:props.previewConfig.procinstid,
    };
    actionClick(historyOperation.value, recallRequst);
  }
  else if (historyOperation.value === "circulate") {
    let circulateRequest: userCirculateRequest;
    circulateRequest = {
      ...userRquest,
      circulateUsers: circulateUsers.value
    };
    actionClick(historyOperation.value, circulateRequest);
  }  
  else if (historyOperation.value === "reminder") {    
    let reminders = reminderCheckedList.value.join(",");
    console.log(reminders);
    let reminderRequest: userReminderRequest;
    reminderRequest = {
      ...userRquest,
      reminderWays: reminders
    };
    actionClick(historyOperation.value, reminderRequest);
  } 




};

const fileList = ref<UploadProps['fileList']>([

]);
const activeKey1 = ref(['2']);
const text = `当前处理人  N9.招采购总监审核：张德力  已处理人：李文）`;
const customStyle =
  'border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden';


// 提示信息弹窗
const msgModalOpen = ref(false);
const handleMsgModalOk = () => {
  msgModalOpen.value = false;
  emit('cancel');
};

const errorMsg = reactive({
  //默认信息类型
  resType: 'suecess',
  //默认提示信息
  resTypeMsg: '',
});

const previewRef = ref(null);

const showPreview = ref(false);
const loading = ref(false);


// 工具栏状态
const {
  toolBar,
  actionClick,
  showReturnModal,
  processStart,
  saveWorkflowdraft,
  sendWork,
  closeDialog,
  initToolBar,
} = useApproveToolbar(previewRef, emit, loading, props.previewConfig, bussid, errorMsg, msgModalOpen);

var saveHeaderDraft = () => {

  toolbarSettings.selectedVaules.humanNodeSelected = humanSelect.value;
  toolbarSettings.selectedVaules.operation = operation.value;
  toolbarSettings.selectedVaules.rejectActivi = rejectActivi.value;
  toolbarSettings.selectedVaules.rejectPath = rejectPath.value;
  toolbarSettings.selectedVaules.afterActivityId = afterActivityId.value;
  toolbarSettings.selectedVaules.transferToUserId = transferToUserId.value;
  toolbarSettings.selectedVaules.signatureType = signatureType.value;
  toolbarSettings.selectedVaules.signatureUsers = signatureUsers.value;
  toolbarSettings.selectedVaules.communicateUsers = communicateUsers.value;
  toolbarSettings.selectedVaules.communicateUsers = circulateUsers.value;

  toolbarSettings.comments = userRquest.comments;

  let toolbarBusinessContext = JSON.stringify(toolbarSettings);
  let wkDraft: userSaveWorkflowDraftRequest = {
    approveUserId: userStore.getUserAccount,
    processInstanceId: props.previewConfig.procinstid,
    processDefinitionId: props.previewConfig.processDefinitionId,
    taskId: props.previewConfig.taskid,
    activityApproveUsers: [],
    handSelectedActivityId: '',
    toolbarSettings: toolbarBusinessContext,
    businessKey: '',
    isRealSaveDraft: true,
    comments: userRquest.comments,
  };
  actionClick('draft', wkDraft);


};


const loadRject = async () => {

  let userRequest: userTaskOperationRequest = {
    taskDefinitionKey: '',
    processInstanceId: props.previewConfig.procinstid,
  }
  const res = await getRejectActivities(userRequest);
  rejectActivis.value = res.result;
}

const updateModifyNodes = (modifyNodes) => {
  modifyNodes.forEach(element => {
    if (element.nodeValues === "")
      element.nodeValues = [];

  });
}
//const newToolbarSetting=ref<any>();

const loadToolBarSettings = async (currentTaskId, processInstanceId, processDefinitionId) => {
  if (processDefinitionId == undefined) {
    processDefinitionId = ""
  }
  const res = await getToolbarSettings({
    taskid: currentTaskId,
    processInstanceId: processInstanceId,
    processDefinitionId: processDefinitionId
  });
  if (res.result.isSavedOperation == "true") {
    let newToolbarSetting = JSON.parse(res.result.businessContext);
    toolbarSettings.commonInfo = newToolbarSetting.commonInfo;
    toolbarSettings.operationTemplate = newToolbarSetting.operationTemplate;
    toolbarSettings.rejectToActivities = newToolbarSetting.rejectToActivities;
    toolbarSettings.humanSelectNodes = newToolbarSetting.humanSelectNodes;
    toolbarSettings.modifyNodes = newToolbarSetting.modifyNodes;
    updateModifyNodes(toolbarSettings.modifyNodes);
    toolbarSettings.transferToUserName = newToolbarSetting.transferToUserName;

    toolbarSettings.willgoNode = newToolbarSetting.willgoNode;
    toolbarSettings.comments = newToolbarSetting.comments;
    toolbarSettings.signaturePersons = newToolbarSetting.signaturePersons;
    toolbarSettings.communicatePersons = newToolbarSetting.communicatePersons;
    toolbarSettings.selectedVaules = newToolbarSetting.selectedVaules;
    userRquest.comments = toolbarSettings.comments;
    humanSelect.value = toolbarSettings.selectedVaules.humanNodeSelected;
    operation.value = toolbarSettings.selectedVaules.operation;
    rejectActivi.value = toolbarSettings.selectedVaules.rejectActivi;
    rejectPath.value = toolbarSettings.selectedVaules.rejectPath;
    afterActivityId.value = toolbarSettings.selectedVaules.afterActivityId;
    transferToUserId.value = toolbarSettings.selectedVaules.transferToUserId;
    signatureType.value = toolbarSettings.selectedVaules.signatureType;
    signatureUsers.value = toolbarSettings.selectedVaules.signatureUsers;
    communicateUsers.value = toolbarSettings.selectedVaules.communicateUsers;
    circulateUsers.value = toolbarSettings.selectedVaules.circulateUsers;
    appendTaskType.value = toolbarSettings.commonInfo.processSubStatus;

  }
  else {
    toolbarSettings.commonInfo = res.result.commonInfo;
    toolbarSettings.operationTemplate = res.result.operationTemplate;
    toolbarSettings.rejectToActivities = res.result.rejectToActivities;
    toolbarSettings.humanSelectNodes = res.result.humanSelectNodes;
    toolbarSettings.modifyNodes = res.result.modifyNodes;
    updateModifyNodes(toolbarSettings.modifyNodes);
    toolbarSettings.willgoNode = res.result.willgoNode;
    toolbarSettings.comments = res.result.comments;
    userRquest.comments = toolbarSettings.comments;
    humanSelect.value = toolbarSettings.selectedVaules.humanNodeSelected;
    operation.value = toolbarSettings.selectedVaules.operation;
    rejectActivi.value = toolbarSettings.selectedVaules.rejectActivi;
    rejectPath.value = toolbarSettings.selectedVaules.rejectPath;
    afterActivityId.value = toolbarSettings.selectedVaules.afterActivityId;
    transferToUserId.value = toolbarSettings.selectedVaules.transferToUserId;
    //signatureType.value = toolbarSettings.selectedVaules.signatureType;
    signatureUsers.value = toolbarSettings.selectedVaules.signatureUsers;
    communicateUsers.value = toolbarSettings.selectedVaules.communicateUsers;
    circulateUsers.value = toolbarSettings.selectedVaules.circulateUsers;
    appendTaskType.value = toolbarSettings.commonInfo.processSubStatus;    
  }
  if (toolbarSettings.commonInfo.processStatus != "isDraft") {
    let time = toolbarSettings.commonInfo.createDatetime;
    let dateTime = new Date(time.replace(/-/g, "/"));  // replace方法将 - 转为 /

    let dateNow = new Date();  // 获取当前时间
    let timeDiff = dateNow.getTime() - dateTime.getTime();  // 时间差的毫秒数
    // timeDiff = 时间戳差值

    let days = Math.floor(timeDiff / (24 * 3600 * 1000)); // 计算出天数
    let leavel1 = timeDiff % (24 * 3600 * 1000); // 计算去除天数后剩余的毫秒数
    let hours = Math.floor(leavel1 / (3600 * 1000)); // 计算天数后剩余的小时数
    let leavel2 = timeDiff % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
    let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数

    startTime.value = `${days}天${hours}时${minutes}分`;

  }  
}

watch(
  () => props.previewConfig,
  () => {
    if (props.previewConfig.form_type == '0') {
      showPreview.value = true;
      loading.value = false;
    }
  },
  {
    immediate: true,
  },
);

defineExpose({
  handleSubmit: onSubMit,
  saveHeaderDraft
});
onMounted(() => {
  //initToolBar(props.previewConfig);
  //loadToolBarSettings(props.previewConfig.taskid, props.previewConfig.procinstid, props.previewConfig.processDefinitionId);
});
</script>


<style lang="less" scoped>
.flex-buttom-box {
  display: flex;
  flex-wrap: wrap-reverse;
  gap: 10px;
}
</style>

<style scoped>
.demo-page-header :deep(tr:last-child td) {
  padding-bottom: 0;
}
</style>